// pages/score/score.js
var app = getApp(); //获取应用实例
const pathLevel = '../../../../'; //路径层级
const quote = require(pathLevel + 'utils/quote.config.js') //统一引入文件
const mta = quote.mta;
const api = quote.api;

const path = quote.paths;
const tools = quote.tools;
const Authorize = quote.Authorize


Page({
    /**
     * 页面的初始数据
     */
    data: {
        fromShare: false,
        pathLevel: pathLevel,
        path: path,
        accuracyData: 0, //精准度
        fluencyData: 0, //流畅度***变更数据名称***
        integrityData: 0, //完整度
        finalScore: 0,
        showModal: true,
        showShareModal: true,
        hidevideo: false,
        muted: false,
        QID: null,
        VideoID: null,
        pushFrom: null,
        loginStatus: app.globalData.loginStatus || false,
        videoUrl: app.globalData.videoUrl,
        openId: app.globalData.openId,
        OpenId_Points: app.globalData.openId, //点赞人的openId
        url: null,
        Title: null,
        ImgUrl: null,
        isImgClick: false,
        UserImgUrl: null,
        UserName: null, //app.globalData.userInfo.nickName
        loadingHidden: false,
        IsPraise: false,
        PointsCount: null, //点赞数
        finishBtnClicked: true,
        hidemodal: true,
        animationRedPaper: '',
        animationData: '',
        UserSpeakingList: null, //用户的录音
        MyworkList: [], //我的作品列表
        VideoSrtList: null, //视频字幕列表
        audioContext: null, //创建音频播放器
        audioUrl: null, //录音音频的地址
        isImgLoad: false,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var self = this
        console.log('打开得分预览页获取到的数据', options)

        self.setData({
            finishBtnClicked: options.finishBtnClicked == 'false' ? false : true,
        })

        var scene = decodeURIComponent(options.scene)
        var sceneArr = scene.split("&")
        if (sceneArr.length == 2) {
            app.globalData.openId = sceneArr[0];
            var QID = sceneArr[1];
            self.setData({
                QID: QID,
            })
            self.getScoreInfoData(sceneArr[0], QID)
            return
        }

        if (options.QID && options.shareOpenId && options.shareFrom) {
            self.setData({
                QID: options.QID,
                loginStatus: app.globalData.loginStatus,
                fromShare: true
            })
            self.getScoreInfoData(options.shareOpenId, options.QID)
            return
        }

        self.setData({
            QID: options.QID,
            loginStatus: app.globalData.loginStatus,
        })
        self.getScoreInfoData(app.globalData.openId, options.QID)

    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function(options) {
        var that = this;

        that.videoContext = wx.createVideoContext('myVideo');

        //创建音频播放器
        that.data.audioContext = wx.createInnerAudioContext();
        var innerAudioContext = that.data.audioContext;
        innerAudioContext.autoplay = true;
        innerAudioContext.obeyMuteSwitch = false;
        innerAudioContext.onCanplay(() => {
            console.log('进入可播放状态');
        })
        innerAudioContext.onPlay(() => {
            console.log('播放录音开始');
            that.setData({
                muted: true
            })
        });
        innerAudioContext.onStop(() => {
            console.log('播放录音停止');
            that.setData({
                muted: false
            })
        });
        innerAudioContext.onEnded(() => {
            console.log('播放录音结束');
            that.setData({
                muted: false
            })
        });
        innerAudioContext.onError((res) => {
            console.log('播放录音发生错误', res, res.errMsg)

        })

        //请求视频字幕数据
        var obj = app.globalData.videoCacheObj[that.data.QID];
        console.log('缓存中的字幕和视频地址', app.globalData.videoCacheObj)
        if (obj) {
            var url = obj[0];
            that.setData({
                url: url,
            })
        }

        mta.Page.init();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function(options) {
        var that = this;
        console.log('onshow', options)

        that.setData({
            loginStatus: app.globalData.loginStatus,
        });

        // console.log(that)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {
        var that = this;

        that.data.audioContext.destroy()
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        /** 取消从分数界面直接返回首页 */
        // wx.switchTab({
        //     url: '../index/index'
        // })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function(params) {
        var that = this;

        that.getScoreInfoData(null, null, function(params) {
            //数据加载完后停止刷新
            setTimeout(() => {
                console.log('停止刷新');
                wx.stopPullDownRefresh();
            }, 1000);
        })

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },
    saveFormId: tools.saveFormId,
    //图片缓冲
    imgOnLoad(e) {
        var that = this;

        // console.log('图片加载完成', e);
        const obj = e.currentTarget.dataset.obj;
        if (e.detail.height) {
            that.setData({
                [obj]: true
            })
        }
    },
    //去个人中心
    gotoMyCenter() {
        var that = this;

        wx.switchTab({
            url: '/' + path.my,
            success: function(res) {
                // success
            }
        })
    },
    videoPlay: function(params) {
        var that = this;

        console.log('视频开始播放了')
    },
    videoPause: function(params) {
        var that = this;

        console.log('视频暂停播放了')
    },
    //视频播放进度回调函数
    timeupdate: function(e) {
        var that = this;

        var startTime = that.data.startTime; //录音片段的开始时间列表
        var currentTime = parseInt(e.detail.currentTime); //视频的当前时间
        var UserSpeakingList = that.data.UserSpeakingList; //用户录音列表
        // console.log('视频播放进度', e.detail.currentTime, e.detail.duration);

        for (let i = 0; i < startTime.length; i++) {
            var ele = Math.floor(startTime[i]);
            if (currentTime == ele) {
                console.log('currentTime', currentTime);
                var audioUrl = app.globalData.apiUrl + UserSpeakingList[i].user_voice_file; //app.globalData.apiUrl https://ies.acadsoc.com.cn
                that.data.audioContext.src = audioUrl;
                // that.data.audioContext.stop();
                // that.data.audioContext.play();
            }
        }

    },
    addPraise: function(params) {
        var self = this
        var openId = self.data.openId // res.currentTarget.dataset.openid || 

        if (openId) {
            var dataDic = {
                OpenId: openId,
                QID: self.data.QID,
                OpenId_Points: self.data.OpenId_Points,
            }
            console.log('点赞', dataDic)
            api.methodWeiXinUserPointPraise({
                dataDic,
                success: (res) => {
                    if (res.data.code != 0) {
                        wx.showModal({
                            title: '温馨提示',
                            showCancel: false,
                            content: res.data.msg,
                        });
                    } else {
                        //点赞成功,刷新界面数据
                        wx.showToast({
                            title: " 点赞成功 ",
                        })
                        setTimeout(() => {
                            self.setData({
                                IsPraise: true,
                                PointsCount: res.data.data.PointCount
                            })
                        }, 1000);
                    }
                },
                fail: (res) => {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: '点赞失败',
                    });
                },
                complete: (res) => {
                    console.log(res);
                }
            });
        }

        app.aldstat.sendEvent('预览-点击点赞');
        mta.Event.stat("scorePreview_userspraise", {});
        if (self.data.finishBtnClicked) {
            app.aldstat.sendEvent('作品-点击点赞');
            mta.Event.stat("mywork_userspraise", {});
        }
    },

    tapMywork: function(e) {
        var that = this;

        var qid = e.currentTarget.dataset.qid;
        that.setData({
            QID: qid
        })
        that.getScoreInfoData(null, qid)
    },
    //获取得分信息
    getScoreInfoData: function(OpenId, Qid, cb) {
        var self = this

        var dataDic = {
            Qid: Qid || self.data.QID,
            OpenId: OpenId || app.globalData.openId,
        };

        api.methodWechatGetUserScoreAndVideoInfo({
            dataDic,
            success: (res) => {
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg,
                    })
                    return;
                } else {
                    console.log('获取分数信息成功', res.data);
                    var startTime = [];
                    var VideoSrtList = res.data.data.VideoSrtList;
                    for (let i = 0; i < VideoSrtList.length; i++) {
                        var ele = VideoSrtList[i].Start_End.split('-')[0];
                        startTime.push(ele)
                    }
                    self.setData({
                        url: app.globalData.videoUrl + res.data.data.VideoUrl, //视频url
                        accuracyData: res.data.data.AccuracyDegree, //精准度
                        fluencyData: res.data.data.FluencyDegree, //流畅度
                        integrityData: res.data.data.CompleteDegree, //完整度
                        PointsCount: res.data.data.PointsCount,
                        finalScore: res.data.data.Score,

                        VideoID: res.data.data.VideoID,
                        IsPraise: res.data.data.IsPraise,
                        UserImgUrl: res.data.data.UserImgUrl,
                        UserName: res.data.data.UserName,
                        Title: res.data.data.Title,
                        ImgUrl: app.globalData.videoUrl + res.data.data.ImgUrl,

                        UserSpeakingList: res.data.data.UserSpeakingList,
                        MyworkList: res.data.data.MyworkList,
                        VideoSrtList: res.data.data.VideoSrtList,
                        startTime: startTime
                    })
                }
            },
            fail: (res) => {
                console.log(res);
                wx.showModal({
                    title: '温馨提示',
                    showCancel: false,
                    content: '获取分数数据失败',
                });
            },
            complete: (res) => {
                // wx.hideLoading();
                console.log(res.data);
                self.setData({
                    loadingHidden: true
                })

                function numberAdd(e, l) {
                    for (let i = 0; i < l; i++) {
                        self.setData({
                            e: i
                        })
                    }
                }
                typeof cb == 'function' && cb();
            }

        });
    },

    // 点击练习记录
    gotoPractice: function() {
        var that = this;

        app.aldstat.sendEvent('得分预览 - 点击练习记录');
        mta.Event.stat("scorePreview_clickpractice", {});
        if (that.data.finishBtnClicked) {
            app.aldstat.sendEvent('作品-点击查看更多');
            mta.Event.stat("mywork_clickpractice", {});
        }

        wx.navigateTo({
            url: '/' + path.practice
        })
    },

    // 点击排行榜
    getuserinfo(e) {
        var that = this;

        app.aldstat.sendEvent('得分预览-点击查看排行');
        mta.Event.stat("scorePreview_clickrankinglist", {});
        if (that.data.finishBtnClicked) {
            app.aldstat.sendEvent('作品-点击查看排名');
            mta.Event.stat("mywork_clickrankinglist", {});
        }

        console.log('e', e)
        var userObj = e.detail
        var getUserInfo = userObj.errMsg.split(':')

        if (getUserInfo[1] != 'ok') {
            Authorize.checkUserInfo(path.authorize, 'scorePreview')
        } else {
            app.globalData.userInfo = userObj.userInfo; //用户信息存入全局
            wx.setStorage({
                key: 'userInfo',
                data: userObj.userInfo,
                success: function(res) {
                    console.log('用户信息存入缓存成功', res)
                }
            })
            wx.navigateTo({
                url: '/' + path.rankList + '?QID=' + that.data.VideoID,
            })
        }
    },


    // 去注册页面
    gotoRegist: function() {

        app.aldstat.sendEvent('得分-点击领取红包');
        mta.Event.stat("score_receiveredenvelopes", {});

        wx.navigateTo({
            url: '/' + path.regist + '?fromPage=score'
        })
    },

    //去登录页面
    gotoLogin: function() {

        app.aldstat.sendEvent('得分预览-点击登录');
        mta.Event.stat("scorePreview_clicklogin", {});

        wx.navigateTo({
            url: '/' + path.login + '?fromPage=score'
        })
    },


    shareCancel: function() {
        this.setData({
            showShareModal: false,
        })
    },

    // 去首页
    gotoIndex: function() {
        wx.switchTab({
            url: '/' + path.index
        })
    },

    //去练习页面
    gotoDetails: function() {
        var that = this

        app.aldstat.sendEvent('作品-点击重新练习');
        mta.Event.stat("scorePreview_clickpracticeagain", {});

        wx.redirectTo({
            url: '/' + path.details + '?QID=' + that.data.QID,
        })
    },

    //分享到朋友圈
    shareToFriends: function() {
        var that = this;

        app.aldstat.sendEvent('作品-点击分享到朋友圈');
        mta.Event.stat("scorePreview_clicksharefriends", {});

        if (that.data.fromShare) {
            wx.switchTab({
                url: `/${path.index}`,
            })
            return
        }
        wx.navigateTo({
            url: `/${path.share}?QID=${that.data.QID}&score=${that.data.finalScore}`
        })

    },

    //关闭红包
    cancel: function(params) {
        var that = this;

        app.aldstat.sendEvent('预览-点击关闭红包');
        mta.Event.stat("scorePreview_clickcancelRedPaper", {});

        that.runAnimate(function(obj) {
            obj.scale(0, 0).step();
        })

        setTimeout(() => {
            that.setData({
                hidevideo: false,
                hidemodal: true
            })
        }, 500);
    },

    //点击完成练习
    finishPractise: function(params) {
        var that = this;

        app.aldstat.sendEvent('预览-点击完成练习');
        mta.Event.stat("scorePreview_clickfinishPractise", {});

        that.setData({
            finishBtnClicked: true,
        })
    },

    //打开红包
    openRedPaper: function(params) {
        var that = this;

        app.aldstat.sendEvent('预览-点击打开红包');
        mta.Event.stat("scorePreview_clickopenRedPaper", {});

        //执行翻转动画
        var animation = wx.createAnimation({
            transformOrigin: "50% 50%",
            duration: 3000,
            timingFunction: "ease",
            delay: 0
        })

        // this.animation = animation

        animation.rotateY(1440).step()

        this.setData({
            animationData: animation.export(),
            openRedPaper: true
        })

        //缓存中写入一个红包已开记录
        var firstOpen = wx.getStorageSync('firstOpen');
        firstOpen.redPaperIsOpened = true;
        console.log('firstOpen', firstOpen);
        wx.setStorageSync('firstOpen', firstOpen);
        app.globalData.redPaperIsOpened = true;

        setTimeout(() => {
            that.setData({
                hidevideo: false,
                hidemodal: true,
            })
            wx.navigateTo({
                url: '/' + path.redPaper
            })
        }, 3500);

    },

    runAnimate: function(action) {
        var that = this;

        var animation = wx.createAnimation({
            transformOrigin: '50% 50%',
            duration: 200,
            timingFunction: 'ease',
            delay: 0
        })

        // that.animation = animation;

        typeof action == 'function' && action(animation)

        that.setData({
            animationRedPaper: animation.export()
        })

    },

    /**
     * 用户点击分享
     */
    onShareAppMessage: function(res) {
        var that = this;

        app.aldstat.sendEvent('预览-点击分享给好友');
        mta.Event.stat("scorePreview_clicksharefriends", {});

        console.log('res', res)

        if (res[0].from === 'button') {
            return {
                path: `${path.scorePreview}?QID=${that.data.QID}&shareOpenId=${app.globalData.openId}&shareFrom=scorePreview`,
                title: '我获得了现金红包，一起来玩吧！',
                success: function(res) {
                    //转发成功
                    console.log('转发成功', res)
                    setTimeout(() => {
                        //每天只弹窗一次获取红包逻辑
                        if (!app.globalData.redPaperIsOpened) {
                            that.runAnimate(function(obj) {
                                obj.scale(0, 0).step();
                            })
                            that.setData({
                                hidemodal: false,
                                hidevideo: true
                            })
                            that.runAnimate(function(obj) {
                                obj.scale(1.2, 1.2).step().scale(0.9, 0.9).step().scale(1, 1).step();
                            })
                        } else {
                            that.setData({
                                hidemodal: true
                            })
                        }
                    }, 1000);
                },
                fail: function(res) {
                    //转发失败
                    console.log('转发失败')
                }
            }
        } else {
            return {
                title: `我在口语秀配音中获得了${that.data.finalScore}分，一起来挑战吧`,
                desc: '天天口语秀',
                path: `${path.scorePreview}?QID=${that.data.QID}&shareOpenId=${app.globalData.openId}&shareFrom=scorePreview`,
                success: function(res) {
                    //转发成功
                    console.log('练习页面转发成功', res)
                    wx.getShareInfo({
                        shareTicket: res.shareTickets[0],
                        success: function(res) { console.log('获取分享练习页面的票据信息成功', res) },
                        fail: function(res) { console.log(res) },
                        complete: function(res) { console.log(res) }
                    })
                },
                fail: function(res) {
                    //转发失败
                }
            }
        }
    },
})